<?php
/**
 * Created by PhpStorm.
 * User: yf
 * Date: 2017/1/23
 * Time: 上午12:06
 */

namespace Conf;


use App\Model\Runner;
use App\Utility\SysConst;
use Core\AbstractInterface\AbstractEvent;
use Core\Component\Di;
use Core\Component\ShareMemory;
use Core\Component\Version\Control;
use Core\Http\Request;
use Core\Http\Response;
use Core\AutoLoader;
use Core\Swoole\AsyncTaskManager;
use Core\Swoole\Server;
use Core\Swoole\Timer;
use think\Db;


class Event extends AbstractEvent
{
    function frameInitialize()
    {
        // TODO: Implement frameInitialize() method.
        date_default_timezone_set('Asia/Shanghai');
        $loader = AutoLoader::getInstance();
        $loader->requireFile('vendor/autoload.php');
    }
    // 初始化完成
    function frameInitialized()
    {
        // TODO: Implement frameInitialized() method.
        //在启动前先清理共享内存信息。
        ShareMemory::getInstance()->clear();
        // 初始化数据库
        $dbConf = Config::getInstance()->getConf('database');
        Db::setConfig($dbConf);
    }


    function beforeWorkerStart(\swoole_server $server)
    {
        // TODO: Implement beforeWorkerStart() method.
    }

    function onStart(\swoole_server $server)
    {
        // TODO: Implement onStart() method.
    }

    function onShutdown(\swoole_server $server)
    {
        // TODO: Implement onShutdown() method.
    }

    function onWorkerStart(\swoole_server $server, $workerId)
    {
        // TODO: Implement onWorkerStart() method.
        //请确定有inotify拓展
        if ($workerId == 0) {
            // 递归获取所有目录和文件
            $a = function ($dir) use (&$a) {
                $data = array();
                if (is_dir($dir)) {
                    //是目录的话，先增当前目录进去
                    $data[] = $dir;
                    $files = array_diff(scandir($dir), array('.', '..'));
                    foreach ($files as $file) {
                        $data = array_merge($data, $a($dir . "/" . $file));
                    }
                } else {
                    $data[] = $dir;
                }
                return $data;
            };
            $list = $a(ROOT . "/App");
            $notify = inotify_init();
            // 为所有目录和文件添加inotify监视
            foreach ($list as $item) {
                inotify_add_watch($notify, $item, IN_CREATE | IN_DELETE | IN_MODIFY);
            }
            // 加入EventLoop
            swoole_event_add($notify, function () use ($notify) {
                $events = inotify_read($notify);
                if (!empty($events)) {
                    //注意更新多个文件的间隔时间处理,防止一次更新了10个文件，重启了10次，懒得做了，反正原理在这里
                    Server::getInstance()->getServer()->reload();
                }
            });
        }


        //为第一个进程添加唤起任务执行的定时器；
        if($workerId == 0){
            Timer::loop(1000,function (){
                $share = ShareMemory::getInstance();
                //请勿使得所有worker全部处于繁忙状态   危险操作
                if($share->get(SysConst::TASK_RUNNING_NUM) < 2){
                    AsyncTaskManager::getInstance()->add(Runner::class);
                }
            });
        }
    }

    function onWorkerStop(\swoole_server $server, $workerId)
    {
        // TODO: Implement onWorkerStop() method.
    }

    function onRequest(Request $request, Response $response)
    {
        // TODO: Implement onRequest() method.
    }

    function onDispatcher(Request $request, Response $response, $targetControllerClass, $targetAction)
    {
        // TODO: Implement onDispatcher() method.
    }

    function onResponse(Request $request,Response $response)
    {
        // TODO: Implement afterResponse() method.
    }

    function onTask(\swoole_server $server, $taskId, $workerId, $taskObj)
    {
        // TODO: Implement onTask() method.
    }

    function onFinish(\swoole_server $server, $taskId, $taskObj)
    {
        // TODO: Implement onFinish() method.
    }

    function onWorkerError(\swoole_server $server, $worker_id, $worker_pid, $exit_code)
    {
        // TODO: Implement onWorkerError() method.
    }
}
